﻿using Autofac;
using IRepositories.Base;
using IServices;
using IServices.Base;
using Repositories.Base;
using Services.Base;
using System.Reflection;

namespace Extensions.ServiceExtensions
{
    public class AutofacModuleRegister:Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // base.Load(builder);
            // builder.RegisterType<ArticleService>().As<IArticleService>();

            //var serviceAssembly = Assembly.Load("Services");
            //// 在load方法中指定要扫描的程序集名称，系统会自动扫描把程序集中所有的接口和实现类都注册到服务中
            //builder.RegisterAssemblyTypes(serviceAssembly).AsImplementedInterfaces();

            //var repositoryAssembly = Assembly.Load("Repositories");
            //builder.RegisterAssemblyTypes(repositoryAssembly).AsImplementedInterfaces();

            // 程序集方式注入
            //var basePath = AppContext.BaseDirectory;
            //var serviceDllFile = Path.Combine(basePath, "Services.dll");
            //var repositoryDllFile = Path.Combine(basePath, "Repositories.dll");
            //if (!(File.Exists(serviceDllFile) && File.Exists(repositoryDllFile)))
            //{
            //    var msg = "Repositories.dll 和 Services.dll 丢失。";
            //    throw new Exception(msg);
            //}
            //var assemblyService = Assembly.LoadFrom(serviceDllFile);
            //builder.RegisterAssemblyTypes(assemblyService).AsImplementedInterfaces();
            //var AssemblyRepository = Assembly.LoadFrom(repositoryDllFile);
            //builder.RegisterAssemblyTypes(AssemblyRepository).AsImplementedInterfaces();

            // 泛型仓储注入
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();
            builder.RegisterGeneric(typeof(BaseServices<>)).As(typeof(IBaseServices<>)).InstancePerDependency();
            var assemblyRepository = Assembly.Load("Repositories");
            builder.RegisterAssemblyTypes(assemblyRepository).AsImplementedInterfaces();
            var assemblyService = Assembly.Load("Services");
            builder.RegisterAssemblyTypes(assemblyService).AsImplementedInterfaces();
        }
    }
}
